import modelEnhance from '@/utils/modelEnhance';
import PageHelper from '@/utils/pageHelper';

/**
 * 当第一次加载完页面时为true
 * 可以用这个值阻止切换页面时
 * 多次初始化数据
 */
let LOADED = false;
export default modelEnhance({
  namespace: 'banners',

  state: {
    bannerList: [],
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname === '/banners' && !LOADED) {
          LOADED = true;
          dispatch({
            type: 'init'
          });
        }
      });
    }
  },

  effects: {
    // 进入页面加载
    *init({ payload }, { call, put, select }) {
      const { pageData } = yield select(state => state.banners);
      yield put({
        type: 'getPageInfo',
        payload: {
          // pageData: pageData.startPage(1, 10)
        }
      });
    },
    // 获取分页数据
    *getPageInfo({ payload }, { call, put }) {
      const { pageData } = payload;
      yield put.resolve({
        type:'@request',
        afterResponse: resp=> resp.data.records,
        payload: {
          valueField: 'bannerList',
          url: '/api/banner/bannerInfoAllList',
          data: {}
          // data: pageData.pageinfoData(),
        }
      })
    },

    *save({payload}, {call, put}){
      const {item} = payload;

      if (item.image && item.image.length> 0 && item.image[0].response) item.image = item.image[0].response.data.fileName; else item.image = null;
      item.is_public=1;
      yield put.resolve({
        type: '@request',
        payload: {
          notice: true,
          data: item,
          url: '/api/banner/addBannerInfo',
        }
      });
      yield put({
        type: 'getPageInfo',
        payload: {}
      });

    },

    *update({payload}, {call, put}){
      const {item} = payload;

      if (item.image && item.image.length> 0 && item.image[0].response) item.image = item.image[0].response.data.fileName; else item.image = null;
      item.is_public=1;
      yield put.resolve({
        type: '@request',
        payload: {
          notice: true,
          data: item,
          url: '/api/banner/updateBannerInfo',
        }
      });
      yield put({
        type: 'getPageInfo',
        payload: {}
      });

    },

    *remove({payload}, {call, put}){
      const {item}= payload;

      yield put.resolve({
        type: '@request',
        payload: {
          notice: true,
          method: 'DELETE',
          url: '/api/banner/deleteBannerInfo/' + item.id,
        }
      });
      yield put({
        type: 'getPageInfo',
        payload: {}
      });

    },
  }
})